<template>
  <a-space>
    <a-select :options="provinces" v-model:value="province" style="width: 120px;" placeholder="选择省/市" @change="onProvinceChange"></a-select>
    <a-select :options="cities" v-model:value="city" style="width: 120px;" placeholder="选择市/区" @change="onCityChange"></a-select>
  </a-space>
</template>

<script setup>
import { ref, computed,onMounted,toRaw,watch } from 'vue';
import pc from '@/assets/pc.json'


const props = defineProps(['value'])
const emit = defineEmits(['update:value'])

const province = ref()
const city = ref()

onMounted(()=>{
  parseProps()
})

watch(()=>props.value,()=>{
  parseProps()
})

const parseProps = ()=>{
  if(props.value && props.value.length >= 2){
    const arr = props.value
    province.value = arr[0]
    city.value = arr[1]
  }
}

const provinces = computed(() => {
  const arr = Object.keys(pc).map(k => {
    return {
      value: k,
      label: k
    }
  })
  return arr
})

const cities = computed(() => {
  const arr = (pc[province.value] || []).map(k => {
    return {
      value: k,
      label: k
    }
  })

  return arr
})

const onProvinceChange = ()=>{
  city.value = null
  emitValue()
}
const onCityChange = ()=>{
  emitValue()
}

const emitValue = ()=>{
  emit('update:value',[toRaw(province.value),toRaw(city.value)])
}

</script>

<style lang="less" scoped></style>